# !/user/bin/env python3
# -*- encoding: utf-8 -*-
"""
@File    :   one_click_acceptance.py
@Date    :   2021-03-29
@Author  :   cecil-y 
@Version :   1.0
@Desc    :   None

一键受理

"""

import requests
from PIL import Image
import json
import time

userId = "ff8080816feb1ab1016ff0b0e6f2157d"
Session = None
token = ""


def create_session():
    global session
    global token
    session = requests.session()
    # session.cookies.set('AntiLeech', '2676165397')
    session.headers.update(
        {
            "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:87.0) Gecko/20100101 Firefox/87.0"
        }
    )
    verifyCode = get_login_verify_code()
    token = login(verifyCode)
    session.cookies.set("Operation-Admin-Token", token)
    session.headers.update(
        {
            "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:87.0) Gecko/20100101 Firefox/87.0",
            "Operation-Back-Token": token,
            "Content-Type": "application/json;charset=utf-8",
        }
    )


# 获得登录验证码
def get_login_verify_code():
    r = session.get(
        url="https://operation.egongzheng.com/operation-back-api/whitelist/captchaimg"
    )
    with open("login_verify_code.jpg", "wb") as f:
        f.write(r.content)
    img = Image.open("login_verify_code.jpg")
    img.show()
    return input("请打开'login_verify_code.jpg'文件后，输入验证码：")


# 登录-获得token
def login(code=""):
    loginParams = {"username": "liwen", "password": "111111", "verifyCode": code}
    r = session.post(
        url="https://operation.egongzheng.com/operation-back-api/login",
        json=loginParams,
    )
    print("operation-back-api/login res:", r.text)
    if r.status_code == 200:
        res = json.loads(r.text)
        if res["status"] == "2000":
            print("登录成功！")
            return res["token"]
        else:
            raise BaseException("登录失败", res)


# 获得订单列表
def get_order_list():
    requestParams = {
        "compounded": "",
        "createTime": [],
        "intermediaryId": "",
        "isQuick": "",
        "orderStatus": ["001", "003"],
        "orgId": "",
        "pageNumber": 1,
        "pageSize": 100,
    }
    r = session.post(
        url="https://operation.egongzheng.com/operation-back-api/business/order/manage/stamp/list",
        json=requestParams,
    )
    if r.status_code == 200:
        res = json.loads(r.text)
        if res["status"] == "2000":
            global orderList
            orderList = res["data"]["list"]
            print(
                "%s | %s | %s | %s | %s | %s | %s | %s | %s | %s "
                % (
                    "订单类型",
                    "订单编号",
                    "申办日期",
                    "申办人",
                    "公证事项",
                    "订单状态",
                    "公证处",
                    "审核人员",
                    "承办人",
                    "中介机构",
                )
            )
            for order in orderList:
                if None != order["intermediaryId"]:
                    print(
                        "%s | %s | %s | %s | %s | %s | %s | %s | %s | %s "
                        % (
                            order["settlementTypeName"],
                            order["orderNum"],
                            order["createFinishTime"],
                            order["userName"],
                            order["notaryItemName"],
                            order["statusName"],
                            order["orgName"],
                            order["allianceUserName"],
                            order["acceptSysUserName"],
                            order["intermediaryName"],
                        )
                    )
                else:
                    print(
                        "%s | %s | %s | %s | %s | %s | %s | %s | %s | %s "
                        % (
                            order["settlementTypeName"],
                            order["orderNum"],
                            order["createFinishTime"],
                            order["userName"],
                            order["notaryItemName"],
                            order["statusName"],
                            order["orgName"],
                            order["allianceUserName"],
                            order["acceptSysUserName"],
                            "",
                        )
                    )
        else:
            raise BaseException(str(res))


# 审核
def sensor_order():
    global orderList
    select_order_list = [
        order
        for order in orderList
        if order["status"] == "001"
        and order["intermediaryId"] in ["44", "29", "32", "45"]
    ]
    if len(select_order_list) == 0:
        print("暂无订单可以受理")
        return
    print("即将受理以下订单：")
    for order in select_order_list:
        if None != order["intermediaryId"]:
            print(
                "%s | %s | %s | %s | %s | %s | %s | %s | %s | %s "
                % (
                    order["settlementTypeName"],
                    order["orderNum"],
                    order["createFinishTime"],
                    order["userName"],
                    order["notaryItemName"],
                    order["statusName"],
                    order["orgName"],
                    order["allianceUserName"],
                    order["acceptSysUserName"],
                    order["intermediaryName"],
                )
            )
        else:
            print(
                "%s | %s | %s | %s | %s | %s | %s | %s | %s | %s "
                % (
                    order["settlementTypeName"],
                    order["orderNum"],
                    order["createFinishTime"],
                    order["userName"],
                    order["notaryItemName"],
                    order["statusName"],
                    order["orgName"],
                    order["allianceUserName"],
                    order["acceptSysUserName"],
                    "",
                )
            )
    if input("输入y确定受理：") == "y":
        for order in select_order_list:
            params = {"orderId": order["id"], "orgId": "1"}
            r = session.post(
                url="https://operation.egongzheng.com/operation-back-api/business/order/manage/audit",
                data=json.dumps(params),
            )
            is_success(r)
            print("确认审核 - 成功，data:", json.loads(r.text)["data"])
            r = session.put(
                url="https://operation.egongzheng.com/operation-back-api/business/order/accept/operation/quick/dispatch",
                data=json.dumps({"orderId": order["id"], "orgId": "1"}),
            )
            is_success(r)
            print("确定公证处 -> 鹭江 成功")
            r = session.put(
                url="https://operation.egongzheng.com/operation-back-api/business/order/accept/operation/examine/order",
                data=json.dumps(params),
            )
            is_success(r)
            print("预审通过 成功")
            r = session.put(
                url="https://operation.egongzheng.com/operation-back-api/business/order/accept/operation/send/order",
                data=json.dumps(params),
            )
            is_success(r)
            print("派单到公证处 成功")
        pass
    pass


def is_success(response):
    time.sleep(2)
    result = json.loads(response.text)
    if result["status"] == "2000":
        return True
    else:
        raise BaseException(str(result))


if __name__ == "__main__":
    create_session()
    get_order_list()
    sensor_order()
    pass